<template>
  <div class="pagination">
    <button @click="updatePage(pageNode - 1)" :disabled="pageNode === 1">
      上一页
    </button>
    <button @click="updatePage(1)" v-show="startOrEnd.start > 1">1</button>
    <span v-show="startOrEnd.start > 2">...</span>
    <button
      v-for="(num, index) in startOrEnd.end - startOrEnd.start + 1"
      :key="num"
      :class="{ active: startOrEnd.start + index === pageNode }"
      :disabled="startOrEnd.start + index === pageNode"
      @click="updatePage(startOrEnd.start + index)"
    >
      {{ startOrEnd.start + index }}
    </button>
    <button v-show="startOrEnd.end < totalPage - 1">···</button>
    <button @click="updatePage(totalPage)">总页数:{{ totalPage }}</button>
    <button
      @click="updatePage(pageNode + 1)"
      :disabled="pageNode === totalPage"
    >
      下一页
    </button>

    <span>共 {{ pages }} 条</span>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pages", "pageSize", "pageNode", "continuous", "updatePage"],
  computed: {
    totalPage() {
      const { pages, pageSize } = this;
      return Math.ceil(pages / pageSize);
    },
    startOrEnd() {
      let start;
      let end;
      const { pageNode, continuous, totalPage } = this;
      if (totalPage < continuous) {
        start = 1;
        end = totalPage;
      } else {
        start = pageNode - (continuous - 1) / 2;
        end = start + (continuous - 1);
        if (start < 1) {
          start = 1;
          end = continuous;
        }
      }
      if (end > totalPage) {
        end = totalPage;
        start = end - continuous + 1;
      }
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      //   cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }
  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>